import React, { useState, useEffect, useRef } from 'react';
import { Input, Button } from 'antd';
import axios from 'axios';

const { TextArea } = Input;

const ContainerLogs = ({ containerId }) => {
  const [logs, setLogs] = useState('');
  const [loading, setLoading] = useState(true);
  const logsRef = useRef(null);

  useEffect(() => {
    if (containerId) {
      fetchLogs();
      const interval = setInterval(fetchLogs, 2000);
      return () => clearInterval(interval);
    }
  }, [containerId]);

  const fetchLogs = async () => {
    try {
      const response = await axios.get(`/api/containers/${containerId}/logs`);
      setLogs(response.data);
      setLoading(false);
      
      // 自动滚动到底部
      if (logsRef.current) {
        logsRef.current.scrollTop = logsRef.current.scrollHeight;
      }
    } catch (error) {
      setLogs('获取日志失败: ' + error.message);
      setLoading(false);
    }
  };

  const clearLogs = () => {
    setLogs('');
  };

  const copyLogs = () => {
    navigator.clipboard.writeText(logs);
  };

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Button onClick={fetchLogs} style={{ marginRight: 8 }}>刷新</Button>
        <Button onClick={copyLogs} style={{ marginRight: 8 }}>复制</Button>
        <Button onClick={clearLogs}>清空</Button>
      </div>
      <TextArea
        ref={logsRef}
        value={logs}
        rows={20}
        readOnly
        placeholder={loading ? '加载中...' : '暂无日志'}
        style={{ 
          fontFamily: 'Consolas, Monaco, monospace',
          fontSize: '12px',
          backgroundColor: '#f5f5f5'
        }}
      />
    </div>
  );
};

export default ContainerLogs;
